package com.woniu.account.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.account.dao.TPermissionMapper;
import com.woniu.account.dao.TRoleMapper;
import com.woniu.account.model.TPermission;
import com.woniu.account.model.TRole;
import com.woniu.account.service.TPermissionService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 吴彦祖
 * @since 2024年04月02日
 */
@Service
public class TPermissionServiceImpl extends ServiceImpl<TPermissionMapper, TPermission> implements TPermissionService {

    @Resource
    private TPermissionMapper permissionMapper;
    @Resource
    private TRoleMapper roleMapper;
    @Override
    public List<TPermission> search() throws Exception {
        QueryWrapper<TPermission> wrapper = new QueryWrapper<TPermission>();
        wrapper.select("id","role_id","resource_id");
        List<TPermission> list = permissionMapper.selectList(wrapper);

        return list;
    }

    @Override
    public void insert(Integer roleId, Integer[] resourceId) throws Exception {
        TRole role = roleMapper.selectById(roleId);
        if(role==null){
            throw new Exception("不存在该角色");
        }
        //删除角色的所有信息
        QueryWrapper<TPermission> wrapper = new QueryWrapper<TPermission>();
        wrapper.eq("role_id",roleId);
        permissionMapper.delete(wrapper);
        //新增角色的所有资源
        TPermission permission = new TPermission();
        for(Integer integer:resourceId){
            permission.setId(null);
            permission.setRoleId(roleId);
            permission.setResourceId(integer);
            permissionMapper.insert(permission);
        }
    }
}
